package com.hdax.ssm.controller;

import com.hdax.ssm.service.PermissionService;
import com.hdax.ssm.service.RolePermissionService;
import com.hdax.ssm.vo.PermissionBean;
import com.hdax.ssm.vo.StateBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.logging.Logger;

@RestController
public class RolePermissionController {
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/toRolePermission")
    public List<PermissionBean> toRolePermission(long roleId){
        List<PermissionBean> pRoots= permissionService.getPermissionByParentId(0);
        for (PermissionBean  p :pRoots) {
            p.setNodes(permissionService.getPermissionByParentId(p.getId()));
        }

        List<Long> pids = rolePermissionService.getRolePermissionByRoleId(roleId);

        for (PermissionBean p : pRoots) {
            StateBean stateBean1 = new StateBean();
            for (Long  id : pids) {
                if(id == p.getId()){
                    stateBean1.setChecked(true);
                    break;
                }
            }
            p.setState(stateBean1);

            for (PermissionBean pNode :p.getNodes()) {
                StateBean stateBean2 = new StateBean();
                for (Long id : pids) {
                    if(id == pNode.getId()){
                        stateBean2.setChecked(true);
                        stateBean1.setChecked(true);
                        break;
                    }
                }
                pNode.setState(stateBean2);
            }
        }

        return pRoots;
    }

    @RequestMapping("/doRolePermission")
    public void doRolePermission(long roleId,String ids){
        rolePermissionService.delAllByRoleId(roleId);
        rolePermissionService.addPermissionByRoleId(roleId,ids);
    }

}
